<template>
	<!-- 聊天界面的外层容器 -->
	<view class="chat-wrapper">
		<!-- 消息展示区域 -->
		<scroll-view class="chat-messages" scroll-y="true" :scroll-into-view="scrollToView">
			<!-- 循环展示每条消息 -->
			<view class="message-item" v-for="(item, index) in msgList" :key="item.id" :id="'msg-' + item.id"
				:class="{ 'other-message': item.fromUser !== loginUserId, 'my-message': item.fromUser === loginUserId }">
				<!-- 撤回通知文本 -->
				<template v-if="item.type === 'withdraw'">
					<view class="withdraw-notification">
						<text>{{ item.text }}</text>
					</view>
				</template>
				<!-- 对方消息 -->
				<template v-else-if="item.fromUser !== loginUserId">
					<image class="avatar" :src="avatarUrl" mode="aspectFill"></image>
					<view class="message-bubble other-bubble">
						<text class="message-text" v-if="!item.voicePath">{{ item.text }}</text>
						<view class="voice-container" v-if="item.voicePath" @click="playVoice(item)">
							<image class="voice-icon"
								:src="playStatus === item.id? '/static/icon/播放.png' : '/static/icon/语音.png'"
								mode="aspectFit"></image>
							<text class="voice-length">{{ Math.floor(item.voiceDuration) }}''</text>
							<progress :percent="item.progress" border-radius="10" color="green" stroke-width="10"
								backgroundColor="#fff" />
						</view>
					</view>
				</template>
				<!-- 自己消息 -->
				<template v-else>
					<view class="message-bubble my-bubble" @longpress="showWithdraw(index)">
						<text class="message-text" v-if="!item.voicePath">{{ item.text }}</text>
						<view class="voice-container" v-if="item.voicePath" @click="playVoice(item)">
							<image class="voice-icon"
								:src="playStatus === item.id? '/static/icon/播放.png' : '/static/icon/发语音.png'"
								mode="aspectFit"></image>
							<!-- 语音保留个位数 -->
							<text class="voice-length">{{ Math.floor(item.voiceDuration) }}''</text>
						</view>
						<!-- 撤回按钮 -->
						<view v-if="showWithdrawButton[index]" class="withdraw-container"
							@click.stop="withdrawMessage(item, index)">
							<text style="color: #ff0000; cursor: pointer;">撤回</text>
						</view>
					</view>
					<image class="avatar " style=" margin-left: 10px;" :src="avatarUrl1"
						mode="aspectFill"></image>
				</template>
			</view>
		</scroll-view>
		<!-- 输入区域 -->
		<view class="input-area">
			<!-- 切换按钮 ,后面会用到-->
			<!-- <image v-if="!isRecording" class="toggle-button" @click="toggleInputMode"
				:src="isTextMode? '/static/icon/按住说话中.png' : '/static/icon/键盘.png'" mode="aspectFit"></image> -->
			<image v-if="!isRecording" class="toggle-button" :src="'/static/icon/键盘.png'" mode="aspectFit"></image>
			<view class="input-box-wrapper" v-if="isTextMode" style="flex-grow: 1; margin: 0 10px;">
				<input v-model="content" hold-keyboard=true cursor-spacing=25px class="input-box" placeholder="请输入内容"
					ref="inputBox" @confirm="send"></input>
			</view>
			<view class="input-box-wrapper" v-else style="flex-grow: 1; margin: 0 10px;">

				<!-- 显示“按住说话”文本 -->
				<input v-if="!isRecording" @touchstart.prevent="startRecord" @touchend.prevent="endRecord"
					class="input-box" placeholder="按住说话" ref="inputBox" disabled></input>

				<!-- 显示播放图标 -->
				<img v-if="isRecording" src="/static/icon/播放.png" style="margin-left: 10px;" />
				<view v-if="isRecording" class="recording-animation"></view>
			</view>
			<image v-if="isTextMode" class="toggle-button" @click="send" :src="'/static/icon/发送.png'" mode="aspectFit">

			</image>
		</view>
		<!-- 语音预览区域 后面会用到-->
		<!-- 	<view v-if="voicePath" class="voice-preview"
			style="background-color: #eaeaea; padding: 18px; display: flex; align-items: center; justify-content: space-between;">
			<button class="send-button" @click="sendVoice">发送语音</button>
			<image class="voice-icon" src="/static/icon/语音.png" mode="aspectFit" style="width: 35px; height: 35px;">
			</image>
			<button class="cancel-button" @click="cancelVoice">取消</button>
		</view> -->
		<!-- 输入模式提示区域 后面会用到-->
		<!-- <view v-if="showInputTip" class="input-tip"
			style="background-color: rgba(0, 0, 0, 0.5); color: #fff; padding: 12px; position: fixed; bottom: 60px; left: 50%; transform: translateX(-50%); border-radius: 8px;">
			<text v-if="isTextMode">文字输入模式</text>
			<text v-if="!isTextMode">语音输入模式</text>
		</view> -->
	</view>
</template>

<script>
	import Vue from 'vue';
	import {
		v4 as uuidv4
	} from 'uuid';
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();

	// 长按指令
	Vue.directive('longpress', {
		bind(el, binding) {
			let start = null;
			el.addEventListener('touchstart', () => {
				start = new Date();
			});
			el.addEventListener('touchend', () => {
				const end = new Date();
				if (end - start >= 1000) { // 按住超过1秒视为长按
					binding.value();
				}
			});
		}
	});

	export default {
		data() {
			return {
				loginUserId: '', // 登录用户ID
				recipientID: '', // 接收消息的用户ID
				content: '', // 输入框内容
				msgList: [], // 消息列表
				isRecording: false, // 是否正在录音
				voicePath: '', // 语音文件路径
				status: 0, // 录音状态
				playStatus: 0, // 播放状态
				scrollToView: '', // 滚动视图
				socketOpen: false, // WebSocket连接状态
				socketMsgQueue: [], // WebSocket消息队列
				time: 0, // 录音时长
				recordedVoice: null, // 录音文件
				isTextMode: true, // 是否处于文字输入模式
				showInputTip: false, // 是否显示输入模式提示
				showWithdrawButton: [], // 控制撤回按钮的显示
				messageSendTimes: {}, // 消息发送时间记录
				isRead: false, // 判断是否已读
				heartbeatInterval: 30000, // 心跳包发送间隔，单位：毫秒
				heartbeatTimer: null, // 心跳包定时器
				lastHeartbeatTime: 0, // 记录最后一次接收到心跳包的时间
				heartbeatCheckInterval: null, // 存储心跳检查定时器的引用
				reconnectAttempts: 0, // 新增一个重连尝试次数的计数器
				maxReconnectAttempts: 5, // 最大重连次数
				isReconnecting: false, // 新增标识是否正在重连
				avatarUrl1:'../../static/icon/默认头像.jpg',//商家头像
				avatarUrl:'../../static/icon/默认头像.jpg',//用户头像
				loginUser:{},
				wb:"wss://absolutuniq.com:8088/imserver"
				//wb:"ws://127.0.0.1:8088/imserver"
			};
		},
		onUnload() {
			uni.closeSocket();
		},
		onLoad(option) {
			debugger
			// 确保option.id有效
			// if (option && option.id&&option.sid) {
			// 	this.avatarUrl1=option.avatarUrl1
			// 	this.avatarUrl=option.avatarUrl
			// 	this.loginUserId=option.sid
			// 	this.recipientID = option.id;
			// } else {
			// 	console.error('Invalid option or missing id');
			// 	return;
			// }
			// 初始化 WebSocket 连接
			console.log('opt----'+option.avatar)
			this.recipientID = option.fromUser
			this.avatarUrl = option.avatar
			let merchant = uni.getStorageSync("loginUser");
			if(merchant.avatarUrl){
				this.avatarUrl1 = this.$baseUrl + merchant.avatarUrl
			} 
			this.connectWebSocket();
			this.initWithdrawButtons();
				// this.loadMessagesFromStorage();
			this.scrollToBottom(); // 滚动到最新消息
			//	this.startHeartbeatCheck(); // 开始检查心跳包
			this.loadSocketMsgQueueFromLocal(); //查询离线消息
		},
		// 用户离开当前页面关闭一系列操作
		onHide() {
			//this.stopHeartbeat();
			// console.log("关闭连接");
			// uni.closeSocket();

			//clearInterval(this.heartbeatCheckInterval);
		},
		methods: {
			// 获取客户的用户头像
			getAvatar(userId) {
				 
				return this.avatarUrl;
			},
			// 连接WebSocket
			connectWebSocket() {
				this.connectSocketStartTime = Date.now();
				// 连接 WebSocket
				this.loginUser = uni.getStorageSync('loginUser');
				console.log(this.loginUser)
				this.loginUserId = this.loginUser.phone
				uni.connectSocket({
					url: this.$wbBaseUrl + '/'+this.loginUser.phone+'/read',
					fail: (err) => {
						console.log('WebSocket 连接失败：', err);
						uni.closeSocket();
						this.reconnectWebSocket();
					}
				});

				// 监听 WebSocket 连接成功
				uni.onSocketOpen(() => {
					console.log('WebSocket连接成功');

					this.socketOpen = true;
					//this.startHeartbeat(); // 发送心跳包
					console.log("连接成功");
					this.reconnectAttempts = 0; // 重置重连次数

					// 发送之前存储的离线消息
					this.socketMsgQueue.forEach(msg => this.sendSocketMessage(msg));
					this.socketMsgQueue = []; // 清空消息队列
				});

				uni.onSocketClose(() => {
					// 表示websocket连接断开
					uni.closeSocket();
					this.socketOpen = false
					//let rec = 'WebSocket连接已关闭，准备重连...'
					//console.log('WebSocket连接已关闭，准备重连...聊天');
					//this.stopHeartbeat() //停止之前的心跳
					//this.reconnectWebSocket(rec); // 重连WebSocket

				});

				uni.onSocketError(() => {
					// 表示websocket连接断开
					uni.closeSocket();
					this.socketOpen = false
					let rec = 'WebSocket连接发生错误，准备重连...'
					console.log('WebSocket连接发生错误，准备重连...');
					//this.stopHeartbeat() //停止之前的心跳
					//this.reconnectWebSocket(rec); // 重连WebSocket

				});
				// 获取历史聊天记录
				const storageKey = this.recipientID;
				this.msgList = uni.getStorageSync(storageKey);
				console.log("键" + storageKey);
				if (!this.msgList) {
					//没有就是空
					this.msgList = [];
				}

				uni.onSocketMessage((res) => {
					debugger
					console.log('收到服务器内容：' + res.data);
					// 处理心跳消息
					if (res.data === 'heartbeat') {
						this.lastHeartbeatTime = Date.now(); // 更新最后一次接收到心跳包的时间
						console.log("收到心跳包" + this.lastHeartbeatTime);
						return
					}
					try {
						const message = JSON.parse(res.data);
						
						if (message.recall) {
							message = this.withdrawMessage(message);
						} else if (message.type === 'messageWithdrawn') {
							this.handleMessageWithdrawnNotification(message.messageId);
						} else {
							message.voiceDuration = message.voiceDuration || 0;
							this.msgList.push(message);
							this.showWithdrawButton.push(false);
							if (message.fromUser === this.loginUserId) {
								this.messageSendTimes[message.id] = Date.now();

							}
							this.updateUserListMsgReceive(message);
							this.saveMessagesToStorage();
							this.scrollToBottom();
						}
					} catch (e) {
						console.error('解析服务器消息失败，原始数据：', res.data, '错误信息：', e);
					}
				});


			},

			// 开始检查心跳包
			startHeartbeatCheck() {

				this.heartbeatCheckInterval = setInterval(() => {
					console.log('正在检查心跳包');
					this.checkHeartbeatTimeout();
				}, 60000); // 每60秒检查一次心跳包是否超时
			},

			checkHeartbeatTimeout() {
				const dt = Date.now();
				const HEARTBEAT_TIMEOUT = 60 * 1000; // 心跳超时时间，这里设置为60秒
				const lo = dt - this.lastHeartbeatTime
				if (lo > HEARTBEAT_TIMEOUT) {
					console.log('心跳包超时，准备重连...');
					// 表示websocket连接断开
					uni.closeSocket();
					this.socketOpen = false
					//this.reconnectWebSocket(); // 触发重连逻辑


				} else {
					console.log("心跳包正常")
				}

			},
			// // 开始发送心跳包
			startHeartbeat() {
				// if (!this.heartbeatTimer) {
				// 	this.heartbeatTimer = setInterval(() => {
				// 		if (this.socketOpen) {
				// 			console.log('发送心跳包客服');
				// 			uni.sendSocketMessage({
				// 				data: 'heartbeat'
				// 			});
				// 		}

				// 	}, this.heartbeatInterval);
				// }
			},


			// 停止发送心跳包
			stopHeartbeat() {
				if (this.heartbeatTimer) {
					clearInterval(this.heartbeatTimer);
					this.heartbeatTimer = null;
				}
			},
		
			// 重连WebSocket
			reconnectWebSocket() {
				if (this.isReconnecting) {
					console.log('已经在重连中，忽略本次重连请求');
					return;
				}
				this.isReconnecting = true;
				const backoffTime = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000); // 最长 30秒重试间隔
				if (this.reconnectAttempts >= this.maxReconnectAttempts) {
					console.log('重连次数超过最大限制，停止重连');
					uni.showToast({
						title: '网络连接失败，请稍后刷新再试',
						icon: 'none'
					});
					this.saveSocketMsgQueueToLocal(); // 保存消息队列到本地存储
					// 达到最大重连次数后刷新页面
					setTimeout(() => {
						const currentPage = getCurrentPages().pop(); // 获取当前页面实例
						if (currentPage) {
							uni.reLaunch({
								url: currentPage.route // 重新加载当前页面
							});
						}
					}, backoffTime);

				} else {

					this.reconnectAttempts++;
					const delay = Math.min(5000 * Math.pow(2, this.reconnectAttempts - 1), 60000);
					const randomDelay = Math.random() * 1000;
					setTimeout(() => {
						// 连接WebSocket
						this.connectWebSocket();
						console.log('正在重连...');
						this.isReconnecting = false; // 重连操作发起后，重置标识
					}, delay + randomDelay);
				}
			},
			
			// 处理消息撤回通知
			handleMessageWithdrawnNotification(messageId) {
				this.msgList = this.msgList.map(item => {
					if (item.id === messageId) {
						item.isWithdrawn = true;
						this.$forceUpdate();
					}
					return item;
				});
			},
			// 初始化撤回按钮
			initWithdrawButtons() {
				this.showWithdrawButton = this.msgList.map(() => false);
			},
			// 保存消息到存储（历史消息）
			saveMessagesToStorage() {
				uni.setStorageSync(this.recipientID, this.msgList);
			},
			// 发送消息
			send() {
				const msg = {
					text: this.content.trim(),
					fromUser: this.loginUser.phone,
					id: Date.now(),
					sendTime: Date.now(), // 记录发送时间
					type: 'text',
					recipientID: this.recipientID,//this.recipientID
				};
				console.log(msg)
				if (msg.text) {
					this.msgList.push(msg);
					this.saveMessagesToStorage();
					this.content = '';
					this.sendSocketMessage(msg); //发送消息
					this.scrollToBottom();
					// 更新用户列表消息发送给对面的（客服使用）
					//this.updateUserListMsg(msg)
				}
			},
			// 更新用户列表消息接收发过来的（客服使用）
			updateUserListMsgReceive(msg) {
				
				let userList = uni.getStorageSync("usersList");
				const existingUser = userList.find(u => u.fromUser === msg.fromUser)
				existingUser.id = msg.id
				existingUser.sendTime = msg.sendTime
				existingUser.text = msg.text || '语音'
				uni.setStorageSync("usersList", userList);
			},
			// 更新用户列表消息发送给对面的（客服使用）
			updateUserListMsg(msg) {
				debugger
				let userList = uni.getStorageSync("usersList");
				const existingUser = userList.find(u => u.fromUser === msg.recipientID)
				if(existingUser){
					existingUser.id = msg.id
					existingUser.sendTime = msg.sendTime
					existingUser.text = msg.text || '语音'
					uni.setStorageSync("usersList", userList);
				}
			},
			// 发送WebSocket消息
			sendSocketMessage(msg) {
				return new Promise((resolve, reject) => {
					// 判断是否连接
					if (this.socketOpen) {
						uni.sendSocketMessage({
							data: JSON.stringify(msg),
							success: () => {
								console.log('消息发送成功，消息内容：', msg);
								resolve();

							},
							fail: (err) => {
								console.error('消息发送失败', err);
								// 如果发送失败，重新加入队列等待下次发送
								this.socketMsgQueue.unshift(msg);
								reject(err);
							}
						});
					} else {
						console.log('WebSocket未连接，将消息添加到队列，消息内容：', msg);
						this.socketMsgQueue.push(msg);
						//this.reconnectWebSocket(rec); // 重连WebSocket
						resolve();
					}
				});
			},
			// 开始录音
			startRecord() {
				clearInterval(this.init);
				this.time = 0;
				this.status = 1;
				this.isRecording = true;
				this.recordedVoice = null;
				recorderManager.start({
					duration: 60000, // 限制最长录音时间为 60 秒
					sampleRate: 16000,
					numberOfChannels: 1,
					encodeBitRate: 96000,
					format: 'mp3',
					frameSize: 10
				});
				recorderManager.onStop((res) => {
					console.log('recorder stop', res);
					this.voicePath = res.tempFilePath;
					this.status = 3;
					this.recordedVoice = res.tempFilePath;
					this.updateTime(res.duration);
					const voiceDuration = this.time;
					if (this.recordedVoice) {
						const lastMessage = this.msgList[this.msgList.length - 1];
						if (lastMessage && lastMessage.type === 'voice') {
							lastMessage.voiceDuration = voiceDuration;
						}
					}
				});
				this.recordingTimer();
			},
			// 结束录音
			endRecord() {
				this.isRecording = false;
				recorderManager.stop();
			},
			// 发送语音消息
			sendVoiceMessage() {
				const msg = {
					voicePath: this.voicePath,
					fromUser: this.loginUserId,
					id: Date.now(),
					progress: 0,
					sendTime: Date.now(),
					type: 'voice',
					voiceDuration: this.time,
				};
				if (this.voicePath) {
					this.msgList.push(msg);
					this.voicePath = ''; // 清除当前的语音路径
					this.sendSocketMessage(msg);
					this.saveMessagesToStorage();
					this.scrollToBottom();
					this.resetVoice();
				}
			},
			// 播放语音
			playVoice(item) {
				if (item.voicePath) {
					if (this.playStatus && this.playStatus !== item.id) {
						innerAudioContext.stop();
					}
					innerAudioContext.src = item.voicePath;
					innerAudioContext.onPlay(() => {
						this.playStatus = item.id;
						this.updateProgress(item);
					});
					innerAudioContext.onError((err) => {
						console.error('播放错误', err);
					});
					innerAudioContext.onEnded(() => {
						this.playStatus = 0;
						item.progress = 0;
					});
					innerAudioContext.play();
				}
			},
			// 录音计时器
			recordingTimer() {
				this.init = setInterval(() => {
					this.time += 1;
					if (this.time >= 60) {
						this.endRecord();
					}
				}, 1000);
			},
			// 更新录音时间
			updateTime(duration) {
				this.time = Math.min(duration / 1000, 60); // 确保不超过60秒
			},
			// 更新播放进度
			updateProgress(item) {
				const duration = innerAudioContext.duration;
				const intervalId = setInterval(() => {
					if (innerAudioContext.paused || innerAudioContext.ended) {
						clearInterval(intervalId);
						return;
					}
					const currentTime = innerAudioContext.currentTime;
					item.progress = (currentTime / duration) * 100;
				}, 1000);
			},
			// 滚动到底部
			// 滚动到最新消息
			scrollToBottom() {
				this.$nextTick(() => {
					console.log("滚动")
					const newMessageId = 'msg-' + this.msgList[this.msgList.length - 1].id;
					this.scrollToView = newMessageId; // 更新scrollToView为最新消息的ID
				});
			},
			// 发送录音
			sendVoice() {
				if (this.recordedVoice) {
					const msg = {
						voicePath: this.recordedVoice,
						fromUser: this.loginUserId,
						id: Date.now(),
						progress: 0,
						sendTime: Date.now(),
						type: 'voice',
						voiceDuration: this.time,
					};
					this.msgList.push(msg);
					this.sendSocketMessage(msg);
					this.saveMessagesToStorage();
					this.scrollToBottom();
					this.resetVoice();
				}
			},
			// 取消录音
			cancelVoice() {
				this.resetVoice();
			},
			// 重置录音
			resetVoice() {
				this.voicePath = '';
				this.recordedVoice = null;
				this.time = 0;
				this.isRecording = false;
			},
			// 切换输入模式
			toggleInputMode() {
				this.isTextMode = !this.isTextMode;
				this.showInputTip = true;
				setTimeout(() => {
					this.showInputTip = false;
				}, 2000);
			},
			// 判断消息是否可撤回
			isWithdrawable(item) {
				if (item.time) {
					return item.time - item.sendTime <= 120 * 1000; // 120秒内可撤回
				} else {
					const currentTime = Date.now();
					return currentTime - item.sendTime <= 120 * 1000; // 120秒内可撤回
				}
			},
			// 显示撤回
			showWithdraw(index) {
				this.$set(this.showWithdrawButton, index, true);
			},
			// 撤回消息逻辑
			withdrawMessage(messageId) {
				const index = this.msgList.findIndex(item => item.id === messageId.id);
				if (index !== -1) {
					const item = messageId;
					if (this.isWithdrawable(messageId)) {
						// 保存原来消息的位置信息
						const originalPosition = {
							fromUser: item.fromUser,
							isMyMessage: item.fromUser === this.loginUserId,
							marginTop: this.$refs[`message-${index}`] ? this.$refs[`message-${index}`].$el.style
								.marginTop : '',
							marginBottom: this.$refs[`message-${index}`] ? this.$refs[`message-${index}`].$el.style
								.marginBottom : '',
							marginLeft: this.$refs[`message-${index}`] ? this.$refs[`message-${index}`].$el.style
								.marginLeft : '',
							marginRight: this.$refs[`message-${index}`] ? this.$refs[`message-${index}`].$el.style
								.marginRight : ''
						};
						// 移除原来的消息
						this.msgList.splice(index, 1);
						let withdrawNotificationText;
						if (item.fromUser === this.loginUserId) {
							withdrawNotificationText = '你撤回了一条消息';
							this.sendWithdrawNotificationToServer(messageId);
						} else {
							withdrawNotificationText = '对方撤回了一条消息';
						}
						const withdrawNotification = {
							text: withdrawNotificationText,
							fromUser: item.fromUser === this.loginUserId ? this.loginUserId : item.fromUser,
							id: item.id,
							sendTime: Date.now(),
							type: 'withdraw',
							isWithdrawNotification: true,
						};

						// 在原来消息的位置插入撤回通知消息
						this.msgList.splice(index, 0, withdrawNotification);
						// 更新视图
						this.$nextTick(() => {
							// 恢复原来消息的位置样式（如果需要）
							if (originalPosition.isMyMessage) {
								this.$refs[`message-${index}`].$el.style.marginRight = originalPosition
									.marginRight;
							} else {
								this.$refs[`message-${index}`].$el.style.marginLeft = originalPosition.marginLeft;
							}
						});
						// this.updateUserListMsgReceive(withdrawNotification);
						this.saveMessagesToStorage();
						return withdrawNotification;
					} else {
						uni.showToast({
							title: '消息已经发送超过两分钟，不可撤回',
							icon: 'none'
						});
					}
				}
			},
			// 发送撤回通知到服务器
			sendWithdrawNotificationToServer(messageId) {
				messageId = {
					...messageId, // 扩展原有的 messageId 对象
					recall: true,
					time: Date.now()
				};
				this.sendSocketMessage(messageId);
			},
			// 存离线消息
			saveSocketMsgQueueToLocal() {
				const storageKey = `${this.loginUserId}_${this.recipientID}`; // 使用模板字符串插入值
				uni.setStorage({
					key: storageKey,
					data: this.socketMsgQueue,
					success: () => {
						console.log('消息队列保存到本地存储成功');
					},
					fail: (err) => {
						console.log('消息队列保存到本地存储失败', err);
					}
				});
			},
			// 获取离线消息
			loadSocketMsgQueueFromLocal() {
				const storageKey = `${this.loginUserId}_${this.recipientID}`; // 使用模板字符串插入值
				uni.getStorage({
					key: storageKey,
					success: (res) => {
						if (res.data) {
							this.socketMsgQueue = res.data;
							res.data.length = 0; // 直接清空数组
							console.log('从本地存储恢复消息队列成功');
						}
					},
					fail: () => {
						console.log('从本地存储恢复消息队列失败');
					}
				});
			},
			// 从存储加载消息
			// loadMessagesFromStorage() {
			// 	const storageKey = this.recipientID;
			// 	const storedMessages = uni.getStorageSync(storageKey);
			// 	if (storedMessages) {
			// 		this.msgList = storedMessages;
			// 		this.initWithdrawButtons();
			// 	}
			// }
		},
		beforeDestroy() {
			clearInterval(this.init);
			innerAudioContext.stop();
			uni.closeSocket();
			clearInterval(this.heartbeatCheckInterval); // 清除心跳检查定时器
		}
	};
</script>

<style>
	/* 消息内容样式 */
	.message-text {
		font-size: 18px;
		color: #333;
		padding: 12px;
		border-radius: 18px;
	}

	/* 聊天界面的样式 */
	.chat-wrapper {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	/* 聊天头部的样式 */
	.chat-header {
		padding: 15px;
		font-size: 22px;
		font-weight: bold;
		border-bottom: 2px solid #ddd;
		background-color: #e0e0e0;
		color: #333;
	}

	/* 消息展示区域的样式 */
	.chat-messages {
		flex-grow: 1;
		overflow-y: auto;
		padding: 15px;
		background-color: #ffffff;
	}

	/* 每条消息的样式 */
	.message-item {
		display: flex;
		margin-bottom: 8px;
	}

	/* 消息气泡的动画 */
	@keyframes fadeIn {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	/* 对方消息的样式 */
	.other-message {
		justify-content: flex-start;
	}

	/* 自己消息的样式 */
	.my-message {
		justify-content: flex-end;
		margin-right: 25px;
	}

	/* 消息容器的样式 */
	.message-container {
		display: flex;
		align-items: flex-start;
	}

	/* 头像容器的样式 */
	.avatar-container {
		width: 60px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 10px;
	}

	/* 头像的样式 */
	.avatar {

		margin-right: 10px;
		width: 45px;
		height: 45px;
		border-radius: 50%;
	}

	/* 消息气泡的样式 */
	.message-bubble {
		background-color: #b3e5fc;
		position: relative;
		padding: 12px;
		border-radius: 18px;
		word-wrap: break-word;
		font-size: 16px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
	}

	/* 对方消息气泡的样式 */
	.other-bubble {
		background-color: #eaeaea;
		margin-bottom: 10px;
		margin-right: 20px;
	}

	/* 自己消息气泡的样式 */
	.my-bubble {
		background-color: #b3e5fc;
		margin-bottom: 10px;
		margin-left: 20px;
	}

	/* 输入区域的样式 */
	.input-area {
		display: flex;
		align-items: center;
		padding: 12px;
		border-top: 1px solid #ddd;
		background-color: #ffffff;
	}

	/* 输入框的样式 */
	.input-box {
		flex-grow: 1;
		padding: 12px;
		border-radius: 25px;
		border: 1px solid #ddd;
		margin: 0 12px;
		font-size: 18px;
		caret-color: #007aff;
		text-align: center;
		/* 尝试使用text-align来居中文本 */
	}

	/* 按钮组的样式 */
	.button-group {
		display: flex;
		align-items: center;
	}

	/* 发送按钮的样式 */
	.send-button {
		/* 增加字体大小 */
		cursor: pointer;
		/* 鼠标悬停时显示指针 */
		transition: background-color 0.3s ease;
		background-color: #1AAD19;
		color: #fff;
		border: none;
		border-radius: 25px;
		padding: 12px 25px;
		font-size: 10px;
		cursor: pointer;
	}

	/* 录音按钮的样式 */
	.record-button {
		background-color: #eaeaea;
		color: #ffffff;
		border-radius: 4px;
		margin-left: 10px;
	}

	/* 语音预览区域的样式 */
	.voice-preview {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 18px;
		border-radius: 8px;
		/* 圆角边框 */
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		/* 添加阴影 */
		background-color: #f0f0f0;
		/* 背景颜色 */
	}

	/* 语音图标的样式 */
	.voice-icon {
		width: 30px;
		height: 23px;
	}

	/* 语音长度的样式 */
	.voice-length {
		font-size: 18px;
		color: #666;
	}

	/* 取消按钮的样式 */
	.cancel-button {
		transition: background-color 0.3s ease;
		background-color: #ddd;
		color: #666;
		border: none;
		border-radius: 25px;
		padding: 12px 25px;
		font-size: 13px;
		cursor: pointer;
	}

	/* 输入模式提示的样式 */
	.input-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		padding: 12px;
		position: fixed;
		bottom: 60px;
		left: 50%;
		transform: translateX(-50%);
		border-radius: 10px;
	}

	/* 撤回容器的样式 */
	.withdraw-container {
		position: absolute;
		top: -5px;
		right: -5px;
		background-color: rgba(255, 0, 0, 0.5);
		color: #ffffff;
		border-radius: 15px;
		padding: 5px 10px;
		font-size: 14px;
		cursor: pointer;
		display: none;
	}

	.toggle-button {
		width: 45px;
		height: 45px;
	}

	/* 鼠标悬浮时显示撤回按钮 */
	.my-bubble:hover .withdraw-container {
		display: block;
	}

	/* 撤回消息的样式 */
	.withdraw-message {
		text-align: center;
		font-size: 14px;
		color: #888;
		margin-top: 5px;
	}

	/* 撤回通知的样式 */
	.withdraw-notification {
		text-align: center;
		padding: 10px;
		margin-top: 5px;
		margin-bottom: 5px;
		margin-left: auto;
		margin-right: auto;
		color: #888;
		font-size: 14px;
	}

	.input-box-wrapper {
		display: flex;
		align-items: center;
		/* 垂直居中对齐 */
	}
</style>